﻿using CHCNetSDKSpace;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace JNCY.Win
{
    public class CHCNetHelper
    {
        public CHCNetSDK.LOGINRESULTCALLBACK LoginCallBack = null;
        private CHCNetSDK.EXCEPYIONCALLBACK m_fExceptionCB = null;
        private CHCNetSDK.MSGCallBack_V31 m_falarmData_V31 = null;

        public Action<ResultInfo> DataCallBack = null;
        public Action<ResultInfo> DataFailCallBack = null;

        //public CHCNetResult Inits()
        //{
        //    bool res = CHCNetSDK.NET_DVR_Init();
        //    if (res == false)
        //    {
        //        return new CHCNetResult { Flag = 0, Content = "设备初始化失败" };
        //    }
        //    else
        //    {
        //        if (CHCNetConfig.IsLog == 1)
        //        {
        //            CHCNetSDK.NET_DVR_SetLogToFile(3, CHCNetConfig.LogPath, true);
        //        }

        //        return new CHCNetResult { Flag = 1, Content = "设备初始化成功" };
        //    }
        //}

        //public CHCNetResult UserLogin()
        //{
        //    int res = 0;

        //    CHCNetSDK.NET_DVR_DEVICEINFO_V30 m_struDeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V30();
        //    res = CHCNetSDK.NET_DVR_Login_V30(CHCNetConfig.Ip, CHCNetConfig.Port, CHCNetConfig.UserName, CHCNetConfig.UserPwd, ref m_struDeviceInfo);

        //    if (res == -1)
        //    {
        //        return new CHCNetResult { Flag = 0, Content = "登录设备失败" };
        //    }

        //    CHCNetData.DeviceUserId = res;
        //    return new CHCNetResult { Flag = 1, Content = "登录设备成功" };
        //}

        public CHCNetResult UserLoginOut()
        {
            if (CHCNetData.DeviceUserId != -1)
            {
                bool res=CHCNetSDK.NET_DVR_Logout(CHCNetData.DeviceUserId);

                if (res)
                {
                    return new CHCNetResult { Flag = 1, Content = "注销登陆设备成功" };
                }
            }

            return new CHCNetResult { Flag = 0, Content = "注销登录设备失败" };
        }

        public CHCNetResult Inits()
        {
            bool res = CHCNetSDK.NET_DVR_Init();
            if (res == false)
            {
                return new CHCNetResult { Flag = 0, Content = "设备初始化失败" };
            }
            else
            {
                if (CHCNetConfig.IsLog == 1)
                {
                    CHCNetSDK.NET_DVR_SetLogToFile(3, CHCNetConfig.LogPath, true);
                }

                CHCNetSDK.NET_DVR_LOCAL_GENERAL_CFG struLocalCfg = new CHCNetSDK.NET_DVR_LOCAL_GENERAL_CFG();
                struLocalCfg.byAlarmJsonPictureSeparate = 1;//控制JSON透传报警数据和图片是否分离，0-不分离(COMM_VCA_ALARM返回)，1-分离（分离后走COMM_ISAPI_ALARM回调返回）

                Int32 nSize = Marshal.SizeOf(struLocalCfg);
                IntPtr ptrLocalCfg = Marshal.AllocHGlobal(nSize);
                Marshal.StructureToPtr(struLocalCfg, ptrLocalCfg, false);

                if (!CHCNetSDK.NET_DVR_SetSDKLocalCfg(17, ptrLocalCfg))  //NET_DVR_LOCAL_CFG_TYPE_GENERAL
                {
                    //iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    //strErr = "NET_DVR_SetSDKLocalCfg failed, error code= " + iLastErr;
                    //MessageBox.Show(strErr);
                }
                Marshal.FreeHGlobal(ptrLocalCfg);

                //设置异常消息回调函数
                if (m_fExceptionCB == null)
                {
                    m_fExceptionCB = new CHCNetSDK.EXCEPYIONCALLBACK(cbExceptionCB);
                }
                CHCNetSDK.NET_DVR_SetExceptionCallBack_V30(0, IntPtr.Zero, m_fExceptionCB, IntPtr.Zero);


                //设置报警回调函数
                if (m_falarmData_V31 == null)
                {
                    m_falarmData_V31 = new CHCNetSDK.MSGCallBack_V31(MsgCallback_V31);
                }
                CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V31(m_falarmData_V31, IntPtr.Zero);

                return new CHCNetResult { Flag = 1, Content = "设备初始化成功" };
            }
        }
        public void cbExceptionCB(uint dwType, int lUserID, int lHandle, IntPtr pUser)
        {
            //异常消息信息类型
            string stringAlarm = "异常消息回调，信息类型：0x" + Convert.ToString(dwType, 16) + ", lUserID:" + lUserID + ", lHandle:" + lHandle;


            FileHelper.Log("错误类型：ox" + Convert.ToString(dwType, 16));
        }


        public bool MsgCallback_V31(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
            AlarmMessageHandle(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);

            return true; //回调函数需要有返回，表示正常接收到数据
        }
        public void AlarmMessageHandle(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            switch (lCommand)
            {
                case CHCNetSDK.COMM_ID_INFO_ALARM://身份证刷卡信息上传
                    ProcessCommAlarm_IDInfoAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                //case CHCNetSDK.COMM_ALARM_ACS://门禁主机报警上传
                //    ProcessCommAlarm_AcsAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                //    break;
            }
        }
        private void ProcessCommAlarm_AcsAlarm(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            CHCNetSDK.NET_DVR_ACS_ALARM_INFO struAcsAlarm = new CHCNetSDK.NET_DVR_ACS_ALARM_INFO();
            uint dwSize = (uint)Marshal.SizeOf(struAcsAlarm);
            struAcsAlarm = (CHCNetSDK.NET_DVR_ACS_ALARM_INFO)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_DVR_ACS_ALARM_INFO));

            //报警设备IP地址
            string strIP = System.Text.Encoding.UTF8.GetString(pAlarmer.sDeviceIP).TrimEnd('\0');
            string fileformat = Path.Combine(SavePicPath(), Guid.NewGuid().ToString("n"));
            //保存抓拍图片
            if ((struAcsAlarm.dwPicDataLen != 0) && (struAcsAlarm.pPicData != IntPtr.Zero))
            {
                string str = string.Format("{0}_{1}.jpg", fileformat, "00");
                FileStream fs = new FileStream(str, FileMode.Create);
                int iLen = (int)struAcsAlarm.dwPicDataLen;
                byte[] by = new byte[iLen];
                Marshal.Copy(struAcsAlarm.pPicData, by, 0, iLen);
                fs.Write(by, 0, iLen);
                fs.Close();
            
            }

            //报警时间：年月日时分秒
            string strTimeYear = (struAcsAlarm.struTime.dwYear).ToString();
            string strTimeMonth = (struAcsAlarm.struTime.dwMonth).ToString("d2");
            string strTimeDay = (struAcsAlarm.struTime.dwDay).ToString("d2");
            string strTimeHour = (struAcsAlarm.struTime.dwHour).ToString("d2");
            string strTimeMinute = (struAcsAlarm.struTime.dwMinute).ToString("d2");
            string strTimeSecond = (struAcsAlarm.struTime.dwSecond).ToString("d2");
            string strTime = strTimeYear + "-" + strTimeMonth + "-" + strTimeDay + " " + strTimeHour + ":" + strTimeMinute + ":" + strTimeSecond;

            string stringAlarm = "门禁主机报警信息，dwMajor：" + struAcsAlarm.dwMajor + "，dwMinor：" + struAcsAlarm.dwMinor + "，卡号："
                + System.Text.Encoding.UTF8.GetString(struAcsAlarm.struAcsEventInfo.byCardNo).TrimEnd('\0') + "，读卡器编号：" +
                struAcsAlarm.struAcsEventInfo.dwCardReaderNo + "，报警触发时间：" + strTime;

            ResultInfo ri = new ResultInfo();
            ri.Flag = 1;
            ri.FaceImg = string.Format("{0}_{1}.jpg", fileformat, "00");


            //if(struAcsAlarm.dwMajor==5 && struAcsAlarm.dwMinor == 22)
            //{
            //    DataFailCallBack(ri);
            //}
        }




        private void ProcessCommAlarm_IDInfoAlarm(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            ResultInfo ri = new ResultInfo();


            CHCNetSDK.NET_DVR_ID_CARD_INFO_ALARM struIDInfoAlarm = new CHCNetSDK.NET_DVR_ID_CARD_INFO_ALARM();
            uint dwSize = (uint)Marshal.SizeOf(struIDInfoAlarm);
            struIDInfoAlarm = (CHCNetSDK.NET_DVR_ID_CARD_INFO_ALARM)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_DVR_ID_CARD_INFO_ALARM));

            //报警设备IP地址
            string strIP = System.Text.Encoding.UTF8.GetString(pAlarmer.sDeviceIP).TrimEnd('\0');

          //  string fileformat =Path.Combine(SavePicPath(), Guid.NewGuid().ToString("n"));
            //保存抓拍图片
            if ((struIDInfoAlarm.dwCapturePicDataLen != 0) && (struIDInfoAlarm.pCapturePicData != IntPtr.Zero))
            {
               // string str = string.Format("{0}_{1}.jpg", fileformat, "00");
                //string str = ".\\picture\\Device_ID_CapturePic_[" + strIP + "]_lUerID_[" + pAlarmer.lUserID + "]_" + iFileNumber + ".jpg";
              //  FileStream fs = new FileStream(str, FileMode.Create);
                int iLen = (int)struIDInfoAlarm.dwCapturePicDataLen;
                byte[] by = new byte[iLen];
                Marshal.Copy(struIDInfoAlarm.pCapturePicData, by, 0, iLen);
                ri.FaceImgByte = by;
               // fs.Write(by, 0, iLen);
              //  fs.Close();
                //iFileNumber++;
            }

            //保存身份证图片数据
            if ((struIDInfoAlarm.dwPicDataLen != 0) && (struIDInfoAlarm.pPicData != IntPtr.Zero))
            {
                //string str = string.Format("{0}_{1}.jpg", fileformat, "01");
                // string str = ".\\picture\\Device_ID_IDPic_[" + strIP + "]_lUerID_[" + pAlarmer.lUserID + "]_" + iFileNumber + ".jpg";
               // FileStream fs = new FileStream(str, FileMode.Create);
                int iLen = (int)struIDInfoAlarm.dwPicDataLen;
                byte[] by = new byte[iLen];
                Marshal.Copy(struIDInfoAlarm.pPicData, by, 0, iLen);

                ri.CardImgByte = by;
                //fs.Write(by, 0, iLen);
                //fs.Close();
              //  iFileNumber++;
            }

            //保存指纹数据
            if ((struIDInfoAlarm.dwFingerPrintDataLen != 0) && (struIDInfoAlarm.pFingerPrintData != IntPtr.Zero))
            {
              //  string str = string.Format("{0}_{1}.data", fileformat, "03");
                //string str = ".\\picture\\Device_ID_FingerPrint_[" + strIP + "]_lUerID_[" + pAlarmer.lUserID + "]_" + iFileNumber + ".data";
               // FileStream fs = new FileStream(str, FileMode.Create);
                int iLen = (int)struIDInfoAlarm.dwFingerPrintDataLen;
                byte[] by = new byte[iLen];
                Marshal.Copy(struIDInfoAlarm.pFingerPrintData, by, 0, iLen);
                //ri.FaceImgByte = by;
                //fs.Write(by, 0, iLen);
                //fs.Close();
              //  iFileNumber++;
            }

            //报警时间：年月日时分秒
            string strTimeYear = (struIDInfoAlarm.struSwipeTime.wYear).ToString();
            string strTimeMonth = (struIDInfoAlarm.struSwipeTime.byMonth).ToString("d2");
            string strTimeDay = (struIDInfoAlarm.struSwipeTime.byDay).ToString("d2");
            string strTimeHour = (struIDInfoAlarm.struSwipeTime.byHour).ToString("d2");
            string strTimeMinute = (struIDInfoAlarm.struSwipeTime.byMinute).ToString("d2");
            string strTimeSecond = (struIDInfoAlarm.struSwipeTime.bySecond).ToString("d2");
            string strTime = strTimeYear + "-" + strTimeMonth + "-" + strTimeDay + " " + strTimeHour + ":" + strTimeMinute + ":" + strTimeSecond;

            string stringAlarm = "身份证刷卡信息，dwMajor：" + struIDInfoAlarm.dwMajor + "，dwMinor：" + struIDInfoAlarm.dwMinor
                + "，身份证号：" + System.Text.Encoding.UTF8.GetString(struIDInfoAlarm.struIDCardCfg.byIDNum).TrimEnd('\0') +
                "，姓名：" + System.Text.Encoding.UTF8.GetString(struIDInfoAlarm.struIDCardCfg.byName).TrimEnd('\0') +
                "，刷卡时间：" + strTime;

           

            ri.Name = System.Text.Encoding.UTF8.GetString(struIDInfoAlarm.struIDCardCfg.byName);
            ri.Sex = struIDInfoAlarm.struIDCardCfg.bySex == 1 ? "男" : "女";
            ri.Nation =getNational( struIDInfoAlarm.struIDCardCfg.byNation.ToString().ToString().PadLeft(2,'0'));
            ri.Address= System.Text.Encoding.UTF8.GetString(struIDInfoAlarm.struIDCardCfg.byAddr);
            ri.CardNo= System.Text.Encoding.UTF8.GetString(struIDInfoAlarm.struIDCardCfg.byIDNum);
            ri.BirthDay = string.Format("{0}年{1}月{2}日", struIDInfoAlarm.struIDCardCfg.struBirth.wYear,
                struIDInfoAlarm.struIDCardCfg.struBirth.byMonth,
                struIDInfoAlarm.struIDCardCfg.struBirth.byDay);

            //ri.CardImg = string.Format("{0}_{1}.jpg", fileformat, "01");
            //ri.FaceImg = string.Format("{0}_{1}.jpg", fileformat, "00");
            ri.Flag = 1;

            if (struIDInfoAlarm.dwMajor==5 && struIDInfoAlarm.dwMinor == 105)
            {
                DataCallBack(ri);
            }
            if(struIDInfoAlarm.dwMajor == 5 && struIDInfoAlarm.dwMinor == 112)
            {
                ri.Flag = 0;
                DataFailCallBack(ri);
            }        
        }


        public CHCNetResult UserLogin()
        {
            CHCNetSDK.NET_DVR_USER_LOGIN_INFO struLogInfo = new CHCNetSDK.NET_DVR_USER_LOGIN_INFO();

            //设备IP地址或者域名
            byte[] byIP = System.Text.Encoding.Default.GetBytes(CHCNetConfig.Ip);
            struLogInfo.sDeviceAddress = new byte[129];
            byIP.CopyTo(struLogInfo.sDeviceAddress, 0);

            //设备用户名
            byte[] byUserName = System.Text.Encoding.Default.GetBytes(CHCNetConfig.UserName);
            struLogInfo.sUserName = new byte[64];
            byUserName.CopyTo(struLogInfo.sUserName, 0);

            //设备密码
            byte[] byPassword = System.Text.Encoding.Default.GetBytes(CHCNetConfig.UserPwd);
            struLogInfo.sPassword = new byte[64];
            byPassword.CopyTo(struLogInfo.sPassword, 0);

            struLogInfo.wPort = ushort.Parse(CHCNetConfig.Port);//设备服务端口号

            struLogInfo.cbLoginResult = LoginCallBack;
            struLogInfo.bUseAsynLogin = false; //是否异步登录：0- 否，1- 是 

            if ((struLogInfo.bUseAsynLogin == true) && (LoginCallBack == null))
            {
                LoginCallBack = new CHCNetSDK.LOGINRESULTCALLBACK(cbLoginCallBack);//注册回调函数                    
            }

            struLogInfo.byLoginMode = 0; //0-Private, 1-ISAPI, 2-自适应
            struLogInfo.byHttps = 0; //0-不适用tls，1-使用tls 2-自适应

            CHCNetSDK.NET_DVR_DEVICEINFO_V40 DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V40();

            //登录设备 Login the device
            CHCNetData.DeviceUserId = CHCNetSDK.NET_DVR_Login_V40(ref struLogInfo, ref DeviceInfo);
            if (CHCNetData.DeviceUserId < 0)
            {
                uint iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                //strErr = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号 Failed to login and output the error code
                //MessageBox.Show(strErr);

                return new CHCNetResult { Flag = 0, Content = "登录设备失败" };
            }
            else
            {
                return new CHCNetResult { Flag = 1, Content = "登录设备成功" };
                //登录成功
                //iDeviceNumber++;
                //string str1 = "" + m_lUserID;
                //listViewDevice.Items.Add(new ListViewItem(new string[] { str1, textBoxIP.Text, "未布防" }));//将已注册设备添加进列表
            }
        }

        public void cbLoginCallBack(int lUserID, int dwResult, IntPtr lpDeviceInfo, IntPtr pUser)
        {
            string strLoginCallBack = "登录设备，lUserID：" + lUserID + "，dwResult：" + dwResult;

        }
        private string SavePicPath()
        {
            string pathdir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar + "";


            string path = Path.Combine(pathdir, "pic");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string paths = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd"));

            if (!Directory.Exists(paths))
            {
                Directory.CreateDirectory(paths);
            }

            return paths;
        }

        public CHCNetResult SetInfo()
        {
            CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
            struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
            struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
            struAlarmParam.byAlarmInfoType = 1;//智能交通设备有效，新报警信息类型
            struAlarmParam.byFaceAlarmDetection = 1;//1-人脸侦测

            if (CHCNetData.DeviceUserId != -1)
            {
                int res=   CHCNetSDK.NET_DVR_SetupAlarmChan_V41(CHCNetData.DeviceUserId, ref struAlarmParam);

                if (res > -1)
                {
                    CHCNetData.DeviceSetId = res;
                    return new CHCNetResult { Flag = 1, Content = "设备布防成功" };
                }
            }
            return new CHCNetResult { Flag = 0, Content = "设备布防失败" };
        }

        public CHCNetResult UnSetInfo()
        {
            if (CHCNetData.DeviceSetId > -1)
            {
                if (CHCNetSDK.NET_DVR_CloseAlarmChan_V30(CHCNetData.DeviceSetId))
                {
                    return new CHCNetResult { Flag = 1, Content = "设备撤防成功" };
                }
            }

            return new CHCNetResult { Flag = 1, Content = "设备撤防失败" };
        }

        public void CleanInfo()
        {
            UnSetInfo();

            if (CHCNetData.DeviceUserId > -1)
            {
                CHCNetSDK.NET_DVR_Logout(CHCNetData.DeviceUserId);
            }

            CHCNetSDK.NET_DVR_Cleanup();
        }

        public static string getNational(string code)
        {
            string result = string.Empty;
            switch (code)
            {
                case "01":
                    result = "汉族";
                    break;
                case "02":
                    result = "蒙古族";
                    break;
                case "03":
                    result = "回族";
                    break;
                case "04":
                    result = "藏族";
                    break;
                case "05":
                    result = "维吾尔族";
                    break;
                case "06":
                    result = "苗族";
                    break;
                case "07":
                    result = "彝族";
                    break;
                case "08":
                    result = "壮族";
                    break;
                case "09":
                    result = "布依族";
                    break;
                case "10":
                    result = "朝鲜族";
                    break;
                case "11":
                    result = "满族";
                    break;
                case "12":
                    result = "侗族";
                    break;
                case "13":
                    result = "瑶族";
                    break;
                case "14":
                    result = "白族";
                    break;
                case "15":
                    result = "土家族";
                    break;
                case "16":
                    result = "哈尼族";
                    break;
                case "17":
                    result = "哈萨克族";
                    break;
                case "18":
                    result = "傣族";
                    break;
                case "19":
                    result = "黎族";
                    break;
                case "20":
                    result = "僳僳族";
                    break;
                case "21":
                    result = "佤族";
                    break;
                case "22":
                    result = "畲族";
                    break;
                case "23":
                    result = "高山族";
                    break;
                case "24":
                    result = "拉祜族";
                    break;
                case "25":
                    result = "水族";
                    break;
                case "26":
                    result = "东乡族";
                    break;
                case "27":
                    result = "纳西族";
                    break;
                case "28":
                    result = "景颇族";
                    break;
                case "29":
                    result = "柯尔克孜族";
                    break;
                case "30":
                    result = "土族";
                    break;
                case "31":
                    result = "达斡尔族";
                    break;
                case "32":
                    result = "仫佬族";
                    break;
                case "33":
                    result = "羌族";
                    break;
                case "34":
                    result = "布朗族";
                    break;
                case "35":
                    result = "撒拉族";
                    break;
                case "36":
                    result = "毛难族";
                    break;
                case "37":
                    result = "仡佬族";
                    break;
                case "38":
                    result = "锡伯族";
                    break;
                case "39":
                    result = "阿昌族";
                    break;
                case "40":
                    result = "普米族";
                    break;
                case "41":
                    result = "塔吉克族";
                    break;
                case "42":
                    result = "怒族";
                    break;
                case "43":
                    result = "乌孜别克族";
                    break;
                case "44":
                    result = "俄罗斯族";
                    break;
                case "45":
                    result = "鄂温克族";
                    break;
                case "46":
                    result = "崩龙族";
                    break;
                case "47":
                    result = "保安族";
                    break;
                case "48":
                    result = "裕固族";
                    break;
                case "49":
                    result = "京族";
                    break;
                case "50":
                    result = "塔塔尔族";
                    break;
                case "51":
                    result = "独龙族";
                    break;
                case "52":
                    result = "鄂伦春族";
                    break;
                case "53":
                    result = "赫哲族";
                    break;
                case "54":
                    result = "门巴族";
                    break;
                case "55":
                    result = "珞巴族";
                    break;
                case "56":
                    result = "基诺族";
                    break;
                default:
                    result = "其他";
                    break;
            }
            return result;
        }
    }

    public class CHCNetResult
    {
        public int Flag { get; set; }

        public string Content { get; set; }
    }
}
